<template>
  <Layout>
    <div class="log-management max-width-1500">
      <div class="header">
        <h2>日志管理</h2>
        <div class="header-actions">
          <el-select
            v-model="searchLevel"
            placeholder="日志级别"
            style="width: 120px; margin-right: 10px;"
            clearable
            @change="fetchLogList"
          >
            <el-option label="DEBUG" value="DEBUG"></el-option>
            <el-option label="INFO" value="INFO"></el-option>
            <el-option label="WARN" value="WARN"></el-option>
            <el-option label="ERROR" value="ERROR"></el-option>
          </el-select>
          
          <el-input
            v-model="searchKeyword"
            placeholder="搜索消息、IP或请求路径"
            style="width: 200px; margin-right: 10px;"
            clearable
            @clear="fetchLogList"
            @keydown.enter="fetchLogList"
          >
            <template #append>
              <el-button :icon="Search" @click="fetchLogList" />
            </template>
          </el-input>
          
          <el-button type="success" @click="fetchLogList" :loading="loading">刷新</el-button>
          
          <el-button
              type="danger"
              @click="handleBatchDelete"
              :disabled="selectedLogs.length === 0"
          >
            批量删除({{ selectedLogs.length }})
          </el-button>
          
          <el-button
              type="danger"
              @click="handleClearLogs"
          >
            清空日志
          </el-button>
        </div>
      </div>
      
      <div class="table-container">
        <el-table
          :data="logList"
          style="width: 100%"
          v-loading="loading"
          element-loading-text="加载中..."
          @selection-change="handleSelectionChange"
          @sort-change="handleSortChange"
        >
          <el-table-column type="selection" width="55" />
          <el-table-column prop="log_id" label="日志ID" width="100" sortable />
          <el-table-column prop="level" label="级别" width="100" sortable>
            <template #default="scope">
              <el-tag v-if="scope.row.level === 'DEBUG'" type="info">{{ scope.row.level }}</el-tag>
              <el-tag v-else-if="scope.row.level === 'INFO'" type="success">{{ scope.row.level }}</el-tag>
              <el-tag v-else-if="scope.row.level === 'WARN'" type="warning">{{ scope.row.level }}</el-tag>
              <el-tag v-else-if="scope.row.level === 'ERROR'" type="danger">{{ scope.row.level }}</el-tag>
              <span v-else>{{ scope.row.level }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="message" label="消息" show-overflow-tooltip />
          <el-table-column prop="tag" label="标签" width="120" show-overflow-tooltip />
          <el-table-column prop="ip_address" label="IP地址" width="150" />
          <el-table-column prop="request_url" label="请求路径" width="200" show-overflow-tooltip />
          <el-table-column prop="user_info" label="用户" width="150">
            <template #default="scope">
              <div v-if="scope.row.user_info">
                <div>{{ scope.row.user_info.name }}({{ scope.row.user_info.account }})</div>
              </div>
              <div v-else>-</div>
            </template>
          </el-table-column>
          <el-table-column prop="createdAt" label="创建时间" width="160" sortable>
            <template #default="scope">
              {{ formatDate(scope.row.createdAt) }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="140" fixed="right">
            <template #default="scope">
              <el-button size="small" @click="handleViewDetail(scope.row)">详情</el-button>
              <el-button 
                size="small" 
                type="danger" 
                @click="handleDeleteLog(scope.row)"
                :loading="deletingLogId === scope.row.log_id"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.limit"
          :page-sizes="[50, 500, 1000]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
      
      <!-- 日志详情弹窗 -->
      <el-dialog
        v-model="detailDialogVisible"
        title="日志详情"
        width="600px"
      >
        <div v-if="currentLog" class="log-detail">
          <el-descriptions :column="1" border>
            <el-descriptions-item label="日志ID">{{ currentLog.log_id }}</el-descriptions-item>
            <el-descriptions-item label="级别">
              <el-tag v-if="currentLog.level === 'DEBUG'" type="info">{{ currentLog.level }}</el-tag>
              <el-tag v-else-if="currentLog.level === 'INFO'" type="success">{{ currentLog.level }}</el-tag>
              <el-tag v-else-if="currentLog.level === 'WARN'" type="warning">{{ currentLog.level }}</el-tag>
              <el-tag v-else-if="currentLog.level === 'ERROR'" type="danger">{{ currentLog.level }}</el-tag>
              <span v-else>{{ currentLog.level }}</span>
            </el-descriptions-item>
            <el-descriptions-item label="标签">{{ currentLog.tag || '-' }}</el-descriptions-item>
            <el-descriptions-item label="消息">{{ currentLog.message }}</el-descriptions-item>
            <el-descriptions-item label="IP地址">{{ currentLog.ip_address || '-' }}</el-descriptions-item>
            <el-descriptions-item label="用户代理">{{ currentLog.user_agent || '-' }}</el-descriptions-item>
            <el-descriptions-item label="请求路径">{{ currentLog.request_url || '-' }}</el-descriptions-item>
            <el-descriptions-item label="请求方法">{{ currentLog.request_method || '-' }}</el-descriptions-item>
            <el-descriptions-item label="创建时间">{{ formatDate(currentLog.createdAt) }}</el-descriptions-item>
            <el-descriptions-item label="更新时间">{{ formatDate(currentLog.updatedAt) }}</el-descriptions-item>
            <el-descriptions-item label="用户信息" v-if="currentLog.user_info">
              <div>
                <div>用户ID: {{ currentLog.user_info.user_id }}</div>
                <div>账号: {{ currentLog.user_info.account }}</div>
                <div>姓名: {{ currentLog.user_info.name }}</div>
              </div>
            </el-descriptions-item>
          </el-descriptions>
        </div>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="detailDialogVisible = false">关闭</el-button>
          </span>
        </template>
      </el-dialog>
    </div>
  </Layout>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search } from '@element-plus/icons-vue'
import Layout from '@/components/Layout.vue'
import type { Log } from '@/api/modules/log'
import { getLogList, getLogDetail, deleteLog, batchDeleteLogs, clearLogs } from '@/api/modules/log'

// 日志列表
const logList = ref<Log[]>([])

// 加载状态
const loading = ref(false)

// 删除日志时的加载状态
const deletingLogId = ref<number | null>(null)

// 选中的日志
const selectedLogs = ref<Log[]>([])

// 搜索级别
const searchLevel = ref('')

// 搜索关键词
const searchKeyword = ref('')

// 排序字段
const sortField = ref('createdAt')

// 排序方式
const sortOrder = ref('DESC')

// 弹窗相关
const detailDialogVisible = ref(false)
const currentLog = ref<Log | null>(null)

// 分页信息
const pagination = ref({
  page: 1,
  limit: 50,
  total: 0
})

// 格式化日期
const formatDate = (dateString: string | undefined) => {
  if (!dateString) return '';
  const date = new Date(dateString);
  return date.toLocaleString('zh-CN');
};

// 处理排序变化
const handleSortChange = (sort: { column: any; prop: string; order: string }) => {
  if (sort.prop) {
    sortField.value = sort.prop;
    sortOrder.value = sort.order === 'ascending' ? 'ASC' : 'DESC';
  } else {
    sortField.value = 'createdAt';
    sortOrder.value = 'DESC';
  }
  fetchLogList();
};

// 获取日志列表
const fetchLogList = async () => {
  loading.value = true
  try {
    const response = await getLogList({
      page: pagination.value.page,
      limit: pagination.value.limit,
      level: searchLevel.value || undefined,
      keyword: searchKeyword.value || undefined,
      sort_field: sortField.value,
      sort_order: sortOrder.value
    })
    
    logList.value = response.data?.list || []
    pagination.value.total = response.data?.pagination?.total || 0
  } catch (error) {
    console.error('获取日志列表失败:', error)
    // 错误信息已经在request.ts的响应拦截器中处理过了，这里不需要再显示
  } finally {
    loading.value = false
  }
}

// 处理分页大小变化
const handleSizeChange = (val: number) => {
  pagination.value.limit = val
  pagination.value.page = 1 // 重置到第一页
  fetchLogList()
}

// 处理当前页变化
const handleCurrentChange = (val: number) => {
  pagination.value.page = val
  fetchLogList()
}

// 处理选择变化
const handleSelectionChange = (val: Log[]) => {
  selectedLogs.value = val
}

// 处理查看详情
const handleViewDetail = async (log: Log) => {
  try {
    const response = await getLogDetail({ log_id: log.log_id! });
    currentLog.value = response.data!;
    detailDialogVisible.value = true;
  } catch (error) {
    console.error('获取日志详情失败:', error);
  }
}

// 处理删除日志
const handleDeleteLog = async (log: Log) => {
  ElMessageBox.confirm(
    `确定要删除该日志记录吗？此操作不可恢复！`,
    '确认删除',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
  .then(async () => {
    if (!log.log_id) return
    
    deletingLogId.value = log.log_id
    try {
      await deleteLog({ log_id: log.log_id })
      ElMessage.success('删除成功')
      // 重新获取日志列表
      fetchLogList()
    } catch (error) {
      console.error('删除日志失败:', error)
      // 错误信息已经在request.ts的响应拦截器中处理过了，这里不需要再显示
    } finally {
      deletingLogId.value = null
    }
  })
  .catch(() => {
    // 用户取消删除
  })
}

// 处理批量删除日志
const handleBatchDelete = async () => {
  ElMessageBox.confirm(
    `确定要删除选中的 ${selectedLogs.value.length} 条日志记录吗？此操作不可恢复！`,
    '确认删除',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
  .then(async () => {
    try {
      const logIds = selectedLogs.value.map(log => log.log_id!).filter(id => id !== undefined);
      if (logIds.length === 0) {
        ElMessage.warning('请选择有效的日志进行删除');
        return;
      }
      
      const response = await batchDeleteLogs({ log_ids: logIds });
      ElMessage.success(`成功删除${response.data?.deleted_count}条日志`);
      // 清空选中项
      selectedLogs.value = [];
      // 重新获取日志列表
      await fetchLogList();
    } catch (error) {
      console.error('批量删除日志失败:', error);
      // 错误信息已经在request.ts的响应拦截器中处理过了，这里不需要再显示
    }
  })
  .catch(() => {
    // 用户取消删除
  })
}

// 处理清空日志
const handleClearLogs = async () => {
  ElMessageBox.confirm(
    `确定要清空所有日志记录吗？此操作不可恢复！`,
    '确认清空',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
  .then(async () => {
    try {
      await clearLogs();
      ElMessage.success('日志已清空');
      // 重新获取日志列表
      await fetchLogList();
    } catch (error) {
      console.error('清空日志失败:', error);
      // 错误信息已经在request.ts的响应拦截器中处理过了，这里不需要再显示
    }
  })
  .catch(() => {
    // 用户取消清空
  })
}

// 组件挂载时获取日志列表
onMounted(() => {
  fetchLogList()
})
</script>

<style scoped>
.log-management {
  padding: 20px;
  background: white;
  border-radius: 4px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  height: 100%;
  display: flex;
  flex-direction: column;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header-actions {
  display: flex;
  align-items: center;
}

.table-container {
  flex: 1;
  overflow: auto;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.log-detail {
  max-height: 60vh;
  overflow-y: auto;
}
</style>